package com.web.nyist.controller.admin.auth;

import com.google.common.collect.Lists;
import com.web.nyist.common.Constant;
import com.web.nyist.common.RoleLevel;
import com.web.nyist.controller.admin.AdminController;
import com.web.nyist.dto.JSONResponse;
import com.web.nyist.dto.admin.AdminMenuButtonDto;
import com.web.nyist.dto.admin.AdminRoleDto;
import com.web.nyist.dto.admin.AdminUserDto;
import com.web.nyist.dto.admin.DataGridPageDto;
import com.web.nyist.model.AdminMenuButton;
import com.web.nyist.model.AdminRole;
import com.web.nyist.service.AdminService;
import com.web.nyist.service.db.AdminMenuService;
import com.web.nyist.service.db.AdminRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by penghuiping on 2/21/15.
 */
@Controller
@RequestMapping(RoleController.BASE_URL)
public class RoleController extends AdminController {

    public static final String BASE_URL = "/admin/auth/role/";

    @Autowired
    AdminRoleService roleService;

    @Autowired
    AdminMenuService menuService;

    @Autowired
    AdminService adminService;


    @RequestMapping(value = "index.do")
    public ModelAndView index(ModelAndView modelAndView, HttpServletRequest request, Long id) throws Throwable {
        AdminUserDto user = (AdminUserDto) request.getSession().getAttribute(Constant.SESSION_USER);
        AdminMenuButtonDto adminMenuButtonDto = adminService.findOneMenuAndButtonById(user.getMenus(), id);
        List<AdminMenuButtonDto> menus = adminService.findTreeMenusEnabled();
        modelAndView.addObject("buttons", adminMenuButtonDto.getChildren());
        modelAndView.addObject("ms", menus);
        modelAndView.addObject("levels", RoleLevel.values());
        modelAndView.setViewName(BASE_URL + "index.htm");
        return modelAndView;
    }


    @RequestMapping(value = "query.do")
    public
    @ResponseBody
    DataGridPageDto query(Integer rows, Integer page, final String searchParams) throws Throwable {
        if (null == page) page = Constant.PAGE_FIRST;
        if (null == rows) rows = Constant.PAGE_SIZE;
        DataGridPageDto<AdminRole> dataGridPageDto = roleService.query(page, rows, searchParams);
        //转换成dto输出
        DataGridPageDto<AdminRoleDto> adminRoleDtoDataGridPageDto = new DataGridPageDto<AdminRoleDto>();
        adminRoleDtoDataGridPageDto.setRows(AdminRoleDto.from(dataGridPageDto.getRows()));
        adminRoleDtoDataGridPageDto.setTotal(dataGridPageDto.getTotal());
        return adminRoleDtoDataGridPageDto;
    }

    @RequestMapping(value = "edit.do")
    public
    @ResponseBody
    AdminRoleDto edit(Long id) throws Throwable {
        AdminRole role = roleService.findOne(id);

        List<AdminMenuButton> roleMenus = menuService.findMenusEnabledByRole(role);
        role.setAdminMenuButtons(roleMenus);

        AdminRoleDto roleDto = new AdminRoleDto(role, AdminMenuButtonDto.from(roleMenus));
        return roleDto;
    }


    @RequestMapping(value = "delete.do")
    public
    @ResponseBody
    JSONResponse delete(Long ids[]) throws Throwable {
        List<AdminRole> users = (List<AdminRole>) roleService.findAll(Lists.newArrayList(ids));
        roleService.delete(users);
        return succeed(true);
    }

    @RequestMapping(value = "editSubmit.do")
    public
    @ResponseBody
    JSONResponse editSubmit(@Valid AdminRoleDto role, Errors errors) throws Throwable {
        if (errors.hasErrors()) {
            return failed("出错啦！");
        }
        //做一些处理，删除一些不需要的数据
        List<AdminMenuButtonDto> menus = role.getMenus();

        if (null != menus) {
            for (int i = (menus.size() - 1); i >= 0; i--) {
                if (null == menus.get(i).getId()) {
                    menus.remove(i);
                }
            }
        }

        List<AdminMenuButton> adminMenuButtons = new ArrayList<AdminMenuButton>();
        for (AdminMenuButtonDto adminMenuButtonDto : menus) {
            adminMenuButtons.add(adminMenuButtonDto.toModel());
        }

        if (null != role.getId() && role.getId() > 0) {
            AdminRole temp = roleService.findOne(role.getId());
            temp.setName(role.getName());
            temp.setDescription(role.getDescription());
            temp.setEnable(role.getEnable());
            temp.setLevel(role.getLevel());
            temp.setAdminMenuButtons(adminMenuButtons);
            roleService.save(temp);
        } else {
            AdminRole role1 = role.toModel();
            role1.setAdminMenuButtons(adminMenuButtons);
            roleService.save(role1);
        }
        return succeed(true);
    }
}
